package com.linln.admin.pcs.controller;


import com.alibaba.fastjson.JSONArray;
import com.linln.admin.config.IDCardEncryptor;
import com.linln.admin.config.SmsUtils;
import com.linln.admin.pcs.service.OrderTempService;
import com.linln.admin.pcs.service.TemplateMessageService;
import com.linln.admin.pcs.service.WechatPayRefundService;
import com.linln.admin.system.service.AppService;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.*;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import com.linln.modules.system.service.OrderPortersService;
import com.linln.modules.system.service.PorterService;
import com.linln.modules.system.service.SmsLogService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.persistence.criteria.Predicate;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * 订单信息管理
 */
@Controller
@RequestMapping("/pcs/order")
public class OrderController {

    @Autowired
    private AppService appService;
    @Autowired
    private PorterRepository porterRepository;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    private PorterPermissionRepository porterPermissionRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private PatientRepository patientRepository;
    @Autowired
    private PatientAdmissionRepository patientAdmissionRepository;
    @Autowired
    private OrderPortersRepository orderPortersRepository;
    @Autowired
    private OrderLogsRepository orderLogsRepository;
    @Autowired
    private  CompanyRepository companyRepository;
    @Autowired
    private  ComplainRepository complainRepository;
    @Autowired
    private PorterService porterService;
    @Autowired
    private WechatPayRefundService wechatPayRefundService;
    @Autowired
    private OrderPortersService orderPortersService;
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private EvaluateRepository evaluateRepository;
    @Autowired
    private MsgRepository msgRepository;
    @Autowired
    private TemplateMessageService templateMessageService;
    @Autowired
    private SmsLogService smsLogService;
    @Autowired
    private OrderTempService orderTempService;
    @Autowired
    private PayRecordRepository payRecordRepository;



    /**
     * 专业陪护列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:order:index")
    public ResponseEntity<?> index(Model model, @EntityParam Porter porter) {
        return appService.layTable(orderRepository, before -> {
                    model.addAttribute("porterName", HttpServletUtil.getParameter("porterName",""));
                    model.addAttribute("orderStatus", HttpServletUtil.getParameter("orderStatus",""));
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("patientName", QuerySpec.LIKE)
                            .withMatcher("depName", QuerySpec.LIKE)
                            .withMatcher("bedNo", QuerySpec.LIKE)
                            .withMatcher("sn", QuerySpec.LIKE)
                            //.withMatcher("project_stage_id", QuerySpec.EQUAL)
                            .withMatcher("ability", QuerySpec.EQUAL)
                            .withMatcher("orderStatus", QuerySpec.EQUAL)
                            .withMatcher("porterName", QuerySpec.LIKE);
                    querySpec.withMatcherValue("type", QuerySpec.EQUAL,"1");
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/order/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    pageResult.getContent().forEach(item -> {
                        Order data = (Order) item;
                        try {
                            data.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(data.getPhone()));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        Company company = companyRepository.getById(data.getCompanyId());
                        if (company!=null) {
                            data.setCompanyName(company.getName());
                        }

                    });
                }

        );

    }



    /**
     * 陪诊/陪检列表页面
     */
    @GetMapping("/index_p")
    @RequiresPermissions("pcs:order:index_p")
    public ResponseEntity<?> index_p(Model model, @EntityParam Order order) {

        return appService.layTable(orderRepository, before -> {
                    model.addAttribute("porterName", HttpServletUtil.getParameter("porterName",""));
                    model.addAttribute("orderStatus", HttpServletUtil.getParameter("orderStatus",""));
                    model.addAttribute("type", HttpServletUtil.getParameter("type",""));
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
//                    List<Object> typeList = new ArrayList<>();
//                    typeList.add(2);
//                    typeList.add(3);
//                    querySpec.withMatcherIn("type", typeList);
                    querySpec.withMatcher("patientName", QuerySpec.LIKE)
                            .withMatcher("orderStatus", QuerySpec.EQUAL)
                            .withMatcher("sn", QuerySpec.LIKE)
                            .withMatcher("porterName", QuerySpec.LIKE);
                    if(order.getType()!=null){
                        querySpec.withMatcherValue("type", QuerySpec.EQUAL,order.getType().toString());
                    }else{
                        querySpec.withMatcherValue("type", QuerySpec.NOT_EQUAL,"1");
                    }
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/order/index_p",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    pageResult.getContent().forEach(item -> {
                        Order data = (Order) item;
                        try {
                            data.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(data.getPhone()));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        Company company = companyRepository.getById(data.getCompanyId());
                        if (company!=null) {
                            data.setCompanyName(company.getName());
                        }

                    });

                }

        );

    }






    /**
     * 订单确认
     */
    @RequestMapping("/form")
    @RequiresPermissions("pcs:order:add")
    public ResponseEntity<?> form(Model model) throws Exception {

        String method = HttpServletUtil.getMethod();
        if (method.equals("GET")) {
            Integer id = HttpServletUtil.getParameterInt("id");
            Order data = orderRepository.getById(id.longValue());
            model.addAttribute("data", data);

            //查询患者信息
            Patient patient = patientRepository.getById(data.getPatientId());
            patient.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
            patient.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone()));
            model.addAttribute("patient", patient);

            //查询患者住院信息
            QuerySpec querySpec = QuerySpec.matching();
            querySpec.withMatcherValue("patientId", QuerySpec.EQUAL,patient.getId().toString())
                    .withMatcherValue("admissionStatus",QuerySpec.EQUAL,"1");
            Specification<PatientAdmission> specification =QuerySpec.of(querySpec);
            PatientAdmission patientAdmission = patientAdmissionRepository.findOne(specification).orElse(null);
            model.addAttribute("patientAdmission", patientAdmission);

            //查询陪护人员信息
            Porter porter = porterRepository.getById(data.getPorterId());

            porter.setAge(HelperUtil.getAge(IDCardEncryptor.aesDecrypt(porter.getCardNo())));
            QuerySpec querySpec1 = QuerySpec.matching();
            querySpec1.withMatcherValue("porterId", QuerySpec.EQUAL, porter.getId().toString());
            //查询服务次数
            Specification<OrderPorters> specification1 = QuerySpec.of(querySpec1);
            porter.setServiceNum((int) orderPortersRepository.count(specification1));
            model.addAttribute("porter", porter);


            Context context = new Context();
            // 将数据加入到 Thymeleaf 上下文中
            context.setVariables(model.asMap());
            // 使用 Thymeleaf 渲染模板
            StringWriter writer = new StringWriter();
            thymeleafViewResolver.getTemplateEngine().process("/pcs/order/form", context, writer);
            return ResponseEntity.ok(writer.toString());
        }else{
            Integer id = HttpServletUtil.getParameterInt("id");
            Order order = orderRepository.getById(id.longValue());
            Integer settlementType = HttpServletUtil.getParameterInt("settlementType");
            order.setSettlementType(settlementType);
            if(order.getIsNeedSignContract()==1){
                order.setOrderStatus(1);
            }else{
                if(settlementType==1){
                    order.setOrderStatus(3);
                    order.setConcludeTime(DateUtils.getDates());
                }else{
                    order.setOrderStatus(4);
                    //修改预交费状态
                    order.setBeforeStatus((byte) 1);
                    order.setIsSettled(2);
                }
            }
            orderRepository.save(order);
            //发送消息
            Msg msg = new Msg();
            msg.setType((byte) 2);
            msg.setPatientId(order.getPatientId());
            msg.setSn(order.getSn());
            msg.setContent("您好!您的订单["+order.getProjectTitle()+"]已确认,我们已通知陪护员赶往您所在的病区,请耐心等待!");
            msg.setStatus((byte) 1);
            msgRepository.save(msg);
            //发送模板消息


            Patient patient = patientRepository.findById(order.getPatientId()).orElse(null);
            if(patient!=null){
                String openId = patient.getOpenid();
                if(openId!=null&& !openId.equals("")){
                    //发送模板消息
                    try {
                        String content = "您的订单("+order.getProjectTitle()+")已确认,请及时进入系统查看!";
                        String ss = IDCardEncryptor.aesDecrypt(patient.getPhone());
                        String r = SmsUtils.sendSms(ss,content);
                        smsLogService .insert(order.getSn(),patient.getPhone(),4,3,patient.getId(),r,r);

//                        String url = "https://test.yuehuio.com/#/pages/order/detail?id="+order.getId();
//                        templateMessageService.sendTemplateMessage(
//                                openId,
//                                "PH8ffR37gOytIEJIt-hOic7WHTnc8M-O1y8Mp2RUooU",
//                                url,
//                                new HashMap<String, String>() {{
//                                    put("thing1", order.getProjectTitle());
//                                    put("phrase5","已确认");
//                                }}
//                        );
                    } catch (Exception e) {
                        // 空catch块直接忽略异常，或添加日志记录
                        // log.error("模板消息发送失败", e);
                    }
                }
            }


            return ResponseEntity.ok(ResultVoUtil.success("成功"));
        }

    }


    /**
     * (五类人员)订单确认
     */
    @RequestMapping("/formWl")
    @RequiresPermissions("pcs:order:add")
    public ResponseEntity<?> formWl(Model model) throws Exception {

        String method = HttpServletUtil.getMethod();
        if (method.equals("GET")) {
            Integer id = HttpServletUtil.getParameterInt("id");
            Order data = orderRepository.getById(id.longValue());
            model.addAttribute("data", data);

            //查询患者信息
            Patient patient = patientRepository.getById(data.getPatientId());
            patient.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
            patient.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone()));
            model.addAttribute("patient", patient);

            //查询患者住院信息
            QuerySpec querySpec = QuerySpec.matching();
            querySpec.withMatcherValue("patientId", QuerySpec.EQUAL,patient.getId().toString())
                    .withMatcherValue("admissionStatus",QuerySpec.EQUAL,"1");
            Specification<PatientAdmission> specification =QuerySpec.of(querySpec);
            PatientAdmission patientAdmission = patientAdmissionRepository.findOne(specification).orElse(null);
            model.addAttribute("patientAdmission", patientAdmission);

            List<Porter> porterList = porterRepository.findAll(QuerySpec.of(QuerySpec.matching().withMatcherValue("companyId", QuerySpec.EQUAL,data.getCompanyId().toString())));
            model.addAttribute("porterList", porterList);

            Context context = new Context();
            // 将数据加入到 Thymeleaf 上下文中
            context.setVariables(model.asMap());
            // 使用 Thymeleaf 渲染模板
            StringWriter writer = new StringWriter();
            thymeleafViewResolver.getTemplateEngine().process("/pcs/order/form_wl", context, writer);
            return ResponseEntity.ok(writer.toString());
        }else{
            Integer id = HttpServletUtil.getParameterInt("id");
            Order order = orderRepository.getById(id.longValue());
            Integer settlementType = 2;
            order.setSettlementType(settlementType);
            order.setOrderStatus(4);
            //修改预交费状态
            order.setBeforeStatus((byte) 1);
            order.setIsSettled(2);
            Integer porterId = HttpServletUtil.getParameterInt("porterId");
            if(porterId==0){
                return ResponseEntity.ok(ResultVoUtil.error("请选择护工"));
            }
            Porter porter = porterRepository.getById(porterId.longValue());
            order.setPorterId(porterId.longValue());
            order.setPorterName(porter.getName());
            order.setPorterPhone(porter.getPhone());
            orderRepository.save(order);
            String startDay = DateUtils.getDate();
            orderTempService.jifei(id.longValue(),startDay);



            //发送消息
            Msg msg = new Msg();
            msg.setType((byte) 2);
            msg.setPatientId(order.getPatientId());
            msg.setSn(order.getSn());
            msg.setContent("您好!您的订单["+order.getProjectTitle()+"]已确认,我们已通知陪护员赶往您所在的病区,请耐心等待!");
            msg.setStatus((byte) 1);
            msgRepository.save(msg);
            //发送模板消息


            Patient patient = patientRepository.findById(order.getPatientId()).orElse(null);
            if(patient!=null){
                String openId = patient.getOpenid();
                if(openId!=null&& !openId.equals("")){
                    //发送模板消息
                    try {
                        String content = "您的订单("+order.getProjectTitle()+")已确认,请及时进入系统查看!";
                        String ss = IDCardEncryptor.aesDecrypt(patient.getPhone());
                        String r = SmsUtils.sendSms(ss,content);
                        smsLogService .insert(order.getSn(),patient.getPhone(),4,3,patient.getId(),r,r);

//                        String url = "https://test.yuehuio.com/#/pages/order/detail?id="+order.getId();
//                        templateMessageService.sendTemplateMessage(
//                                openId,
//                                "PH8ffR37gOytIEJIt-hOic7WHTnc8M-O1y8Mp2RUooU",
//                                url,
//                                new HashMap<String, String>() {{
//                                    put("thing1", order.getProjectTitle());
//                                    put("phrase5","已确认");
//                                }}
//                        );
                    } catch (Exception e) {
                        // 空catch块直接忽略异常，或添加日志记录
                        // log.error("模板消息发送失败", e);
                    }
                }
            }


            return ResponseEntity.ok(ResultVoUtil.success("成功"));
        }

    }

    /**
     * 订单退款
     */
    @RequestMapping("/refund")
    @RequiresPermissions("pcs:order:refund")
    public ResponseEntity<?> refund(Model model) throws Exception {
        Integer id = HttpServletUtil.getParameterInt("id");
        Order order = orderRepository.getById(id.longValue());
        Double total = order.getTotal();
        Double balance = order.getBalance();
        Double refund = balance-total;
        Map<String, String> msgMap = null;
        PayParam payParam =  new PayParam();
        payParam.setOutTradeNo(order.getSn());
        payParam.setTotalFee(String.valueOf(balance));
        payParam.setRefundFee(String.valueOf(refund));
        payParam.setType(3);
        msgMap = wechatPayRefundService.handleRefund(payParam);
        String code = msgMap.get("code");
        String msg = msgMap.get("msg");
        if(code.equals("0")){
            return ResponseEntity.ok(ResultVoUtil.error(msg));
        }else{
            return ResponseEntity.ok(ResultVoUtil.success(msg));
        }
    }


    /**
     * 修改状态
     * @param model
     * @param order
     * @return
     * @throws Exception
     */
    @RequestMapping("/state")
    @RequiresPermissions("pcs:order:state")
    public ResponseEntity<?> state(Model model, @EntityParam Order order) throws Exception {

        return appService.save(orderRepository, (data) -> {

            // 校验数据
            return ValidationUtil.validateFields(new ArrayList<>());

        }, (data) -> {
            // 处理数据
            Order origin = orderRepository.getById(order.getId());
            origin.setOrderStatus(order.getOrderStatus());
            return origin;

        }, (data) -> {
            // 更新后操作
            Order order2 = (Order) data;
            Order order1 = orderRepository.getById(order2.getId());
            if(order1.getOrderStatus()==-1){
                QuerySpec querySpec = QuerySpec.matching();
                querySpec.withMatcherValue("orderId", QuerySpec.EQUAL,order1.getId().toString())
                        .withMatcherValue("porterId", QuerySpec.EQUAL,order1.getPorterId().toString());
                Specification<OrderPorters> specification = QuerySpec.of(querySpec);
                OrderPorters orderPorters = orderPortersRepository.findOne(specification).orElse(null);
                if(orderPorters!=null){
                    orderPorters.setServiceStatus(-1);
                    orderPortersRepository.save(orderPorters);
                }
            }else if(order1.getOrderStatus()==5){
                int orderStatus = order1.getOrderStatus();
                //1 实时结算 2 延时结算
                int settlementType = order1.getSettlementType();
                //将退还费用
                Double total = order1.getTotal();
                Double balance = order1.getBalance();
                Double refund = balance-total;
                if (refund>0&&settlementType==1){
                    PayParam payParam =  new PayParam();
                    payParam.setOutTradeNo(order1.getSn());
                    payParam.setTotalFee(String.valueOf(balance));
                    payParam.setRefundFee(String.valueOf(refund));
                    payParam.setType(3);
                    Map<String, String> msgMap = null;
                    try {
                        msgMap = wechatPayRefundService.handleRefund(payParam);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    String code = msgMap.get("code");
                    String msg = msgMap.get("msg");
                    //更新订单状态
                    order1.setOrderStatus(5);
                    order1.setEndTime(DateUtils.getDates());
                    //更新护工表限制服务人数
                    porterService.updatePorter(0,order1.getPorterId(),order1.getNumberLimit(),order1.getId(),2);
                    orderRepository.save(order1);
                    //更新记录
                    orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),2,"",DateUtils.getDates(),1,order1.getType());

                }else{
                    order1.setOrderStatus(5);
                    order1.setEndTime(DateUtils.getDates());
                    //更新护工表限制服务人数
                    porterService.updatePorter(Long.parseLong(order1.getDepId()),order1.getPorterId(),order1.getNumberLimit(),order1.getId(),2);
                    orderRepository.save(order1);
                    //更新记录


                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcherValue("orderId", QuerySpec.EQUAL, String.valueOf(order1.getId()))
                            .withMatcherValue("serviceStatus", QuerySpec.EQUAL,"1");
                    OrderPorters orderPorters = orderPortersRepository.findOne(QuerySpec.of(querySpec)).orElse(null);
                    //获取当前时间且时间格式设置为 2025-01-01 00:00:00
                    Date now = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String nowStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,now);


                    if(orderPorters!=null){
                        //将原护工服务状态改为已结束
                        orderPorters.setServiceStatus(2);
                        orderPorters.setTimeEnd(nowStr);
                        //orderPorters.setUpdateTime(nowStr);
                        orderPorters.setType(3);
                        orderPortersRepository.save(orderPorters);

                    }
                    //发送消息
                    Msg msg = new Msg();
                    msg.setType((byte) 5);
                    msg.setPatientId(order1.getPatientId());
                    msg.setSn(order1.getSn());
                    msg.setContent("您好!您的订单["+order1.getProjectTitle()+"]由陪护公司手动终止服务,若继续服务请重新下单");
                    msg.setStatus((byte) 1);
                    msgRepository.save(msg);

                   // orderPortersService.updatePorterOrder(order1.getId(),order1.getPorterId(),0L,order1.getCompanyId(),2,"",DateUtils.getDates(),1,order1.getType());

                }



//                QuerySpec querySpec = QuerySpec.matching();
//                querySpec.withMatcherValue("orderId", QuerySpec.EQUAL,order1.getId().toString())
//                        .withMatcherValue("porterId", QuerySpec.EQUAL,order1.getPorterId().toString());
//                Specification<OrderPorters> specification = QuerySpec.of(querySpec);
//                OrderPorters orderPorters = orderPortersRepository.findOne(specification).orElse(null);
//                if(orderPorters!=null){
//                    orderPorters.setServiceStatus(2);
//                    orderPortersRepository.save(orderPorters);
//                }
            }

        });

    }

    /**
     * 专业陪护订单详情
     */
    @GetMapping("/detail")
    @RequiresPermissions("pcs:order:detail")
    public String detail(@RequestParam Long id, Model model) throws Exception{
        Order data = orderRepository.getById(id);
        Company company = companyRepository.getById(data.getCompanyId());
        data.setCompanyName(company.getName());
        String createTimeStr = HelperUtil.dateFormat(data.getCreateTime(),"yyyy-MM-dd HH:mm");
        model.addAttribute("createTimeStr", createTimeStr);
        model.addAttribute("data", data);

        //查询患者信息
        Patient patient = patientRepository.getById(data.getPatientId());
        if(patient!=null){
            patient.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
            patient.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone()));
        }

        model.addAttribute("patient", patient);

        //查询患者住院信息
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("patientId", QuerySpec.EQUAL,patient.getId().toString())
                .withMatcherValue("admissionStatus",QuerySpec.EQUAL,"1");
        Specification<PatientAdmission> specification =QuerySpec.of(querySpec);
        PatientAdmission patientAdmission = patientAdmissionRepository.findOne(specification).orElse(null);
        model.addAttribute("patientAdmission", patientAdmission);

        //查询服务人员信息
        QuerySpec querySpec1 = QuerySpec.matching();
        querySpec1.withMatcherValue("orderId", QuerySpec.EQUAL,data.getId().toString());
        querySpec1.withMatcherValue("porterId", QuerySpec.NOT_EQUAL,null);
        List<OrderPorters> orderPorters = orderPortersRepository.findAll(QuerySpec.of(querySpec1));
        AtomicInteger isShowPorter = new AtomicInteger(1);

        if(!orderPorters.isEmpty()){
            orderPorters.forEach(item -> {
                if(item.getPorterId()!=null){
                    Porter porter = porterRepository.getById(item.getPorterId());
                    item.setPorter(porter);
                    item.setTimeStarStr(item.getTimeStar());
                    item.setTimeEndStr(item.getTimeEnd());
                }else{
                    item.setPorter(null);
                    isShowPorter.set(0);
                }

            });
        }
        model.addAttribute("isShowPorter", isShowPorter);
        model.addAttribute("orderPorters", orderPorters);

        //查询服务日志
        QuerySpec querySpec2 = QuerySpec.matching();
        querySpec2.withMatcherValue("orderId", QuerySpec.EQUAL,data.getId().toString());
        Specification<OrderLogs> specification2 = QuerySpec.of(querySpec2);
        List<OrderLogs> orderLogsList = orderLogsRepository.findAll(specification2);
        orderLogsList.forEach(item -> {
           // item.setImgsList(Arrays.asList(item.getImgs().split("\\|")));
            item.setCreateTimeStr(HelperUtil.dateFormat(item.getCreateTime(),"yyyy年MM月d日"));
            item.setTimes(HelperUtil.dateFormat(item.getCreateTime(),"HH:mm"));
        });


        // 使用Map来按createDay和porterId分组
        Map<String, List<OrderLogs>> groupedByCreateDayAndPorterId = orderLogsList.stream().collect(Collectors.groupingBy(log ->
                log.getCreateDay() + "-" + log.getPorterId()
        ));
        List<OrderLogs> orderLogs = new ArrayList<>();
        for (Map.Entry<String, List<OrderLogs>> entry : groupedByCreateDayAndPorterId.entrySet()) {
            String key = entry.getKey();
            List<OrderLogs> value = entry.getValue();

            OrderLogs orderLogs1 = value.get(0);
            List<OrderLogImg> orderLogImgList = new ArrayList<>();
            value.forEach(item -> {
                OrderLogImg orderLogImg = new OrderLogImg();
                orderLogImg.setTimes(item.getTimes());
                orderLogImg.setImg(item.getImgs());
                orderLogImgList.add(orderLogImg);
            });
            orderLogs1.setOrderLogImgList(orderLogImgList);
            orderLogs.add(orderLogs1);
       }
        if(orderLogs.size()>0){
            model.addAttribute("orderLogs", orderLogs);
        }



        //查询投诉
        QuerySpec querySpec3 = QuerySpec.matching();
        querySpec3.withMatcherValue("sn", QuerySpec.EQUAL,data.getSn());
        List<Complain> complainList = complainRepository.findAll(QuerySpec.of(querySpec3));
        if(complainList.size()>0){
            Complain complain = complainList.get(0);
            if(complain.getPics()!=null){
                // 将字符串转换为JSON数组
                complain.setPicsList(JSONArray.parseArray(complain.getPics(), String.class));

            }
            QuerySpec querySpec4 = QuerySpec.matching();
            querySpec4.withMatcherValue("porterId", QuerySpec.EQUAL, complain.getPorterId().toString());
            //查询服务次数
            complain.setServiceNum((int) orderPortersRepository.count(QuerySpec.of(querySpec4)));
            complain.setCreateTimeStr(HelperUtil.dateFormat(complain.getCreateTime(),"yyyy-MM-dd HH:mm"));
            model.addAttribute("complain",complain);
        }

        //查询评价
        QuerySpec querySpec5 = QuerySpec.matching();
        querySpec5.withMatcherValue("sn", QuerySpec.EQUAL,data.getSn());
        List<Evaluate> evaluateList = evaluateRepository.findAll(QuerySpec.of(querySpec5));
        if(evaluateList.size()>0){
            Evaluate evaluate = evaluateList.get(0);

            QuerySpec querySpec6 = QuerySpec.matching();
            querySpec6.withMatcherValue("porterId", QuerySpec.EQUAL, evaluate.getPorterId().toString());
            //查询服务次数
            evaluate.setServiceNum((int) orderPortersRepository.count(QuerySpec.of(querySpec6)));
            evaluate.setCreateTimeStr(HelperUtil.dateFormat(evaluate.getCreateTime(),"yyyy-MM-dd HH:mm"));
            model.addAttribute("evaluate",evaluate);
        }












//        model.addAttribute("orderLogs", orderLogs);




        return "/pcs/order/detail";
    }

    /**
     * 更换护工
     */
    @GetMapping("/chageporter")
    @RequiresPermissions("pcs:order:chageporter")
    public ResponseEntity<?> chageporter(Model model, @EntityParam Order order) {

        return appService.layTable(porterRepository, before -> {
                    model.addAttribute("orderId", order.getId());
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("name", QuerySpec.LIKE);
//                    User user = ShiroUtil.getSubject();
//                    if (user.getType()!=null&&user.getType().equals("2")) {
//                        Long companyId = user.getCompanyId();
//                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
//                    }
                    querySpec.withMatcherValue("isStatus", QuerySpec.EQUAL,"1");
                    Order orderInfo = orderRepository.getById(order.getId());
                    querySpec.withMatcherValue("companyId", QuerySpec.EQUAL, String.valueOf(orderInfo.getCompanyId()));
                    //查询该科室是否有满足权限的护工  (查出订单的depid)
                    List<Object> depIds = new ArrayList<>();
                    depIds.add(0);
                    if (ObjectUtils.isNotEmpty(orderInfo.getDepId())){
                        depIds.add(Long.valueOf(orderInfo.getDepId()));
                    }
                    querySpec.withMatcherIn("depId", depIds);
                    querySpec.withMatcherValue("leastLimit", QuerySpec.LT,String.valueOf(orderInfo.getNumberLimit()));

                    QuerySpec queryDep = QuerySpec.matching();
                    queryDep.withMatcherValue("status", QuerySpec.EQUAL,"1")
                            .withMatcherValue("depId", QuerySpec.EQUAL,orderInfo.getDepId())
                            .withMatcherValue("companyId", QuerySpec.EQUAL, String.valueOf(orderInfo.getCompanyId()))
                            .withMatcherValue("verifyStatus", QuerySpec.EQUAL,"1");
                    List<PorterPermission> permissionList = porterPermissionRepository.findAll(QuerySpec.of(queryDep));
                    List<Object> porters = new ArrayList<>();
                    for (PorterPermission porterPermission : permissionList){
                        porters.add(porterPermission.getPorterId());
                    }
                    querySpec.withMatcherIn("id", porters);

                    return QuerySpec.of(querySpec);
                },

                "/pcs/order/chageporter",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    pageResult.getContent().forEach(item -> {
                        // 对每一项数据进行处理
                        Porter data = (Porter) item;
                        try {
                            data.setAge(HelperUtil.getAge(IDCardEncryptor.aesDecrypt(data.getCardNo())));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }


                        Specification specification = (Specification<PorterPermission>) (root, query, cb) -> {
                            Predicate predicate = cb.conjunction();  // 初始条件
                            predicate = cb.and(predicate, cb.equal(root.get("porterId"), data.getId()));
                            predicate = cb.and(predicate, cb.equal(root.get("verifyStatus"), 1));

                            return predicate;
                        };
                        List<PorterPermission> porterPermissions = porterPermissionRepository.findAll(specification);
                        data.setPorterPermissions(porterPermissions);
                    });
                }

        );

    }

    /**
     * 保存更换护工数据
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/savechageporter")
    @RequiresPermissions("pcs:order:chageporter")
    public ResponseEntity<?> savechageporter(Model model) throws Exception {
        Integer orderId = HttpServletUtil.getParameterInt("orderId");
        // 获取选中的护工id
        String newPorterId = HttpServletUtil.getParameter("ids");

        //查询订单
        Order order = orderRepository.getById(orderId.longValue());
        //原护工id
        Long oldPorterId = order.getPorterId();

        //查询当前订单项目的限制人数
        int numberLimit = order.getNumberLimit();
        //原护工执行退单操作
        porterService.updatePorter(Long.parseLong(order.getDepId()),oldPorterId,numberLimit,orderId,2);

        //新护工执行下单操作
        porterService.updatePorter(Long.parseLong(order.getDepId()),Long.valueOf(newPorterId),numberLimit,0,1);
        //更新护工记录
       // orderPortersService.updatePorterOrder(Long.valueOf(orderId),oldPorterId,Long.valueOf(newPorterId),order.getCompanyId(),1,"","",3,order.getType());

        //新护工信息
        Porter newPorter = porterRepository.getById(Long.valueOf(newPorterId));
        order.setPorterId(Long.valueOf(newPorterId));
        order.setPorterName(newPorter.getName());
        orderRepository.save(order);


        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("orderId", QuerySpec.EQUAL,orderId.toString())
                .withMatcherValue("serviceStatus", QuerySpec.EQUAL,"1");
        OrderPorters orderPorters = orderPortersRepository.findOne(QuerySpec.of(querySpec)).orElse(null);
        //获取当前时间且时间格式设置为 2025-01-01 00:00:00
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,now);


        if(orderPorters!=null){
            //将原护工服务状态改为已结束
            if(order.getOrderStatus()==2){
                orderPorters.setServiceStatus(2);
            }else{
                orderPorters.setServiceStatus(3);
            }
            orderPorters.setTimeEnd(nowStr);
            //orderPorters.setUpdateTime(nowStr);
            orderPorters.setType(3);
            orderPortersRepository.save(orderPorters);

        }

        //插入新的护工记录
        OrderPorters orderPortersNew = new OrderPorters();
        orderPortersNew.setOrderId(orderId.longValue());
        orderPortersNew.setCompanyId(order.getCompanyId());
        orderPortersNew.setPorterId(Long.valueOf(newPorterId));
        orderPortersNew.setServiceStatus(1);
        orderPortersNew.setTimeStar(nowStr);
        orderPortersNew.setType(1);
        orderPortersNew.setOrderType(order.getType());
        orderPortersNew.setStatus((byte) 1);
        orderPortersRepository.save(orderPortersNew);



        return ResponseEntity.ok(ResultVoUtil.success("成功"));

    }

    /**
     * 获取订单支付列表
     * @param model
     * @param payRecord
     * @return
     */
    @GetMapping("/paylist")
    @RequiresPermissions("pcs:order:state")
    public ResponseEntity<?> paylist(Model model, @EntityParam PayRecord  payRecord) {

        return appService.layTable(payRecordRepository, before -> {
                    model.addAttribute("orderNo", HttpServletUtil.getParameter("orderNo",""));
                    model.addAttribute("operatorStatus", HttpServletUtil.getParameter("operatorStatus","1"));
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("operatorStatus", QuerySpec.EQUAL)
                            .withMatcher("payBackStatus", QuerySpec.EQUAL)
                            .withMatcher("orderNo", QuerySpec.LIKE);
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/order/paylist",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    pageResult.getContent().forEach(item -> {


                    });

                }

        );

    }


    /**
     * 获取订单退款列表
     * @param model
     * @param payRecord
     * @return
     */
    @GetMapping("/refundlist")
    @RequiresPermissions("pcs:order:state")
    public ResponseEntity<?> refundList(Model model, @EntityParam PayRecord  payRecord) {

        return appService.layTable(payRecordRepository, before -> {
                    model.addAttribute("orderNo", HttpServletUtil.getParameter("orderNo",""));
                    model.addAttribute("operatorStatus", HttpServletUtil.getParameter("operatorStatus","2"));
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("operatorStatus", QuerySpec.EQUAL)
                            .withMatcher("backStatus", QuerySpec.EQUAL)
                            .withMatcher("orderNo", QuerySpec.LIKE);
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/order/refundlist",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    pageResult.getContent().forEach(item -> {


                    });

                }

        );

    }






    /**
     * 保存更换护工数据(old)
     * @param model
     * @return
     * @throws Exception

    @RequestMapping("/savechageporter")
    @RequiresPermissions("pcs:order:chageporter")
    public ResponseEntity<?> savechageporter(Model model) throws Exception {
        Integer orderId = HttpServletUtil.getParameterInt("orderId");
        // 获取选中的护工id
        String ids = HttpServletUtil.getParameter("ids");
        //查询订单
        Order order = orderRepository.getById(orderId.longValue());
        //原护工id
        Long oldPorterId = order.getPorterId();

        //查询当前订单项目的限制人数










        order.setPorterId(Long.valueOf(ids));
        Porter porter = porterRepository.getById(Long.valueOf(ids));
        order.setPorterName(porter.getName());
        orderRepository.save(order);

        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("orderId", QuerySpec.EQUAL,orderId.toString())
                .withMatcherValue("serviceStatus", QuerySpec.EQUAL,"1");
        OrderPorters orderPorters = orderPortersRepository.findOne(QuerySpec.of(querySpec)).orElse(null);
        //获取当前时间且时间格式设置为 2025-01-01 00:00:00
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,now);


        if(orderPorters!=null){
            //将原护工服务状态改为已结束
            if(order.getOrderStatus()==2){
                orderPorters.setServiceStatus(2);
            }else{
                orderPorters.setServiceStatus(3);
            }
            orderPorters.setTimeEnd(nowStr);
            //orderPorters.setUpdateTime(nowStr);
            orderPorters.setType(3);
            orderPortersRepository.save(orderPorters);

        }
        //新增一条记录
        OrderPorters orderPortersNew = new OrderPorters();
        orderPortersNew.setOrderId(orderId.longValue());
        orderPortersNew.setCompanyId(order.getCompanyId());
        orderPortersNew.setPorterId(Long.valueOf(ids));
        orderPortersNew.setServiceStatus(1);
        orderPortersNew.setTimeStar(nowStr);
        orderPortersNew.setType(1);
        orderPortersNew.setOrderType(order.getType());
        orderPortersNew.setStatus((byte) 1);
        orderPortersRepository.save(orderPortersNew);

        return ResponseEntity.ok(ResultVoUtil.success("成功"));

    } */





}
